<template>
    <div class="container">
        <div class="handle-box">
                <el-form ref="form" :model="searchform" label-width="90px" class="flex">
                     <el-form-item label="负责区域：">
                        <el-input v-model="searchform.name" placeholder="请输入地区" class="handle-input mr10"  @input="mohu()"></el-input>
                    </el-form-item>
                    <el-form-item label="姓名：">
                        <el-input v-model="searchform.streetname" placeholder="请输入姓名" class="handle-input mr10"  @input="streetmohu()"></el-input>
                    </el-form-item>
                    <el-form-item label="人员类型：">
                        <el-input v-model="searchform.nametype" placeholder="请输入人员类型" class="handle-input mr10" @input="communitmohu()"></el-input>
                    </el-form-item>
                    <el-form-item class="flex">
                        <el-button type="primary" icon="el-icon-search">搜索</el-button>
                        <!-- <el-button type="danger" icon="el-icon-circle-close">清空</el-button> -->
                        <el-button type="success" icon="el-icon-circle-plus-outline" @click="addlistdatadiglog()">新增</el-button>
                        <el-button style="padding:0;border:0">
                             <el-upload
                            action="/上传文件的接口"
                            :on-change="onChange"
                            :auto-upload="false"
                            :show-file-list="false"
                            accept=".xls, .xlsx"  class="upload">
                        <el-button type="warning" icon="el-icon-folder-add" style="width:97px;height:33px">导入列表</el-button>
                        <!-- <el-button type="warning" icon="el-icon-folder-add" style="width:97px;height:33px">导出列表</el-button> -->
                    </el-upload>
                        </el-button>
                        <el-button type="primary" @click="exportToExcel()" style="background:#409EFF;border:1px solid #409EFF">导出列表</el-button>
                    </el-form-item>
                </el-form>
            </div>
            <el-table
                :data="tableData.slice((currentPage-1)*pageSize,currentPage*pageSize)"
            >
                <el-table-column type="index" :index="indexMethod" label="ID"></el-table-column>
                <el-table-column prop="Collector_NAME" label="指导员姓名"></el-table-column>
                <el-table-column prop="PHONE" label="手机号"></el-table-column>
                <el-table-column prop="PWD" label="登陆密码"></el-table-column>
                <el-table-column prop="STREET_NAME" label="所属街道"></el-table-column>
                <el-table-column prop="COMMUNITY_NAME" label="所属社区"></el-table-column>
                <el-table-column prop="VILLAGE_NAME" label="所属小区"></el-table-column>
                <el-table-column prop="REMARK" label="备注"></el-table-column>
                <el-table-column label="操作" width="180" align="center">
                    <template slot-scope="scope">
                        <el-button
                            type="text"
                            icon="el-icon-edit"
                            @click="handleEdit(scope.$index, scope.row)"
                        >编辑</el-button> |
                        <el-button
                            type="text"
                            @click="handleDelete(scope.$index, scope.row)" style="color:red"
                        >删除</el-button> |
                        <el-button
                            type="text"
                            @click="routerhandleEdit()" style="color:#2A47BD"
                        >积分管理</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                    background
                    layout="total, sizes, prev, pager, next, jumper"
                    :current-page="currentPage"  
                    :page-size="pageSize"
                    :total="tableData.length"
                    @size-change="handleSizeChange"
                    @current-change="handlePageChange"
                ></el-pagination>
            </div>
               <!-- 编辑弹出框 -->
            <el-dialog v-dialogDrag title="编辑指导员" :visible.sync="editVisible" width="50%">
                <el-form ref="editform" :model="editform" label-width="70px" class="display">
                    <el-form-item label="所属地区：" :label-width="labelwidth" class="wid50">
                       <el-select v-model="editform.PARENT_ID" placeholder="请选择" @change="changevalue">
                          <el-option v-for="item in options" :key='item.REGION_ID' :label="item.REGION_NAME" :value="item.REGION_ID" >
                          </el-option>
                        </el-select>
                    </el-form-item>                    
                    <el-form-item label="所属街道：" :label-width="labelwidth" class="wid50">
                       <el-select v-model="editform.STREET_NAME" placeholder="请选择" @change="changecommunitvalue">
                          <el-option v-for="item in optionsstreet" :key='item.STREET_ID' :label="item.STREET_NAME" :value="item.STREET_ID">
                          </el-option>
                        </el-select>
                    </el-form-item>                   
                    <el-form-item label="所属社区：" :label-width="labelwidth" class="wid50">
                        <el-select v-model="editform.COMMUNITY_NAME" placeholder="请选择">
                          <el-option v-for="item in optionscommunit" :key='item.COMMUNITY_ID' :label="item.COMMUNITY_NAME" :value="item.COMMUNITY_ID">
                          </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="小区：" :label-width="labelwidth" class="wid50">
                        <el-input v-model="editform.VILLAGE_NAME"></el-input>
                    </el-form-item>
                    <el-form-item label="指导员姓名：" :label-width="labelwidth" class="wid50">
                        <el-input v-model="editform.Collector_NAME"></el-input>
                    </el-form-item>
                    <el-form-item label="手机号：" :label-width="labelwidth" class="wid50">
                        <el-input v-model="editform.PHONE"></el-input>
                    </el-form-item>
                    <el-form-item label="登陆密码：" :label-width="labelwidth" class="wid50">
                        <el-input v-model="editform.PWD"></el-input>
                    </el-form-item>
                    <el-form-item label="备注：" :label-width="labelwidth" class="wid50">
                        <el-input v-model="editform.REMARK"></el-input>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="editVisible = false">取 消</el-button>
                    <el-button type="primary" @click="saveEdit">确 定</el-button>
                </span>
            </el-dialog>
            <!-- 新增弹出框 -->
            <el-dialog v-dialogDrag title="新增收集员" :visible.sync="addeditVisible" width="50%">
                <el-form ref="form" :model="addform" label-width="70px" class="display">
                    <el-form-item label="所属地区：" :label-width="labelwidth" class="wid50">
                       <el-select v-model="addform.PARENT_ID" placeholder="请选择" @change="changevalue">
                          <el-option v-for="item in options" :key='item.REGION_ID' :label="item.REGION_NAME" :value="item.REGION_ID" >
                          </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="所属街道：" :label-width="labelwidth" class="wid50">
                       <el-select v-model="addform.STREET_ID" placeholder="请选择" @change="changecommunitvalue">
                          <el-option v-for="item in optionsstreet" :key='item.STREET_ID' :label="item.STREET_NAME" :value="item.STREET_ID">
                          </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="所属社区：" :label-width="labelwidth" class="wid50">
                        <el-select v-model="addform.COMMUNITY_ID" placeholder="请选择" @change="changeplot">
                          <el-option v-for="item in optionscommunit" :key='item.COMMUNITY_ID' :label="item.COMMUNITY_NAME" :value="item.COMMUNITY_ID">
                          </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="小区：" :label-width="labelwidth" class="wid50">
                        <el-select v-model="addform.VILLAGE_ID" placeholder="请选择">
                          <el-option v-for="item in optionsplot" :key='item.VILLAGE_ID' :label="item.VILLAGE_NAME" :value="item.VILLAGE_ID">
                          </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="指导员姓名：" :label-width="labelwidth" class="wid50">
                        <el-input v-model="addform.NAME"></el-input>
                    </el-form-item>
                    <el-form-item label="手机号：" :label-width="labelwidth" class="wid50">
                        <el-input v-model="addform.PHONE"></el-input>
                    </el-form-item>
                    <el-form-item label="登陆密码：" :label-width="labelwidth" class="wid50">
                        <el-input v-model="addform.PWD"></el-input>
                    </el-form-item>
                    <el-form-item label="备注：" :label-width="labelwidth" class="wid50">
                        <el-input v-model="addform.REMARK"></el-input>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="addeditVisible = false">取 消</el-button>
                    <el-button type="primary" @click="addsaveEdit(addform)">确 定</el-button>
                </span>
            </el-dialog>
        </div>
</template>
<script>
import '../../assets/css/common.css'

export default {
    data(){
        return{
              currentPage:1, //初始页
                pageSize:10,    //    每页的数据
                userList: [],
                address:'',
                name:'',
                value1: '',
                labelswidth: '160px',
                labelwidth: '120px',
                addform:{},
                optionstype:[{
                    typeID:1,
                    typeName: '指导员'
                },{
                    typeID:2,
                    typeName: '巡查员'
                }],
                editform:'',
                searchform : {
                name: '',
                streetname: '',
                communitname: ''
                },
                form:{
                    integral: '',
                    score: '',
                    remaining: '',
                    chuyuintegral: '',
                    chuyuscore: '',
                    chuyuremaining: '',
                    youhaiintegral:'',
                    youhaiscore: '',
                    youhairemaining: '',
                    qitaintegral: '',
                    qitascore: '',
                    qitaremaining: ''
                },
            options: [],
            optionsstreet:[],
            optionscommunit:[],
            optionsplot: [],
            tableData: [
            ],
            multipleSelection: [],
            delList: [],
            editVisible: false,
            pageTotal: 0,
            form: {},
            idx: -1,
            id: -1,
            addeditVisible:false,
            imgBroadcastList:[], // 储存旬中的图片列表
            imgsStr: '', // 后端需要的多张图base64字符串，分割
            dialogImageUrl: '',
            diaLogForm: {
              goodsName:'', // 商品名称字段
              imgBroadcastList:[], // 储存选中的图片列表
              imgsStr:''   // 后端需要的多张图base64字符串 , 分割
            },
        }
    },
    created() {
        this.getdata();
        this.getselect()
    },
    methods: {
        indexMethod(index) {
          return index + 1;
        },
        // 图片选择后 保存在 diaLogForm.imgBroadcastList 对象中
   imgBroadcastChange (file, fileList) {
    //    this.createMiniQrcode(URL.createObjectURL(file.raw)
    const isLt2M = file.size / 1024 / 1024 < 2 // 上传头像图片大小不能超过 2MB
    if (!isLt2M) {
     this.diaLogForm.imgBroadcastList = fileList.filter(v => v.uid !== file.uid)
     this.$message.error('图片选择失败，每张图片大小不能超过 2MB,请重新选择!')
    } else {
        // console.log(URL.createObjectURL(file.raw))
        this.imgsStr = URL.createObjectURL(file.raw)
     this.diaLogForm.imgBroadcastList.push(file)
    //  console.log(this.diaLogForm.imgBroadcastList.push(file))
    //  this.submitDialogData()
    }
   },
   // 有图片移除后 触发
   imgBroadcastRemove (file, fileList) {
    this.diaLogForm.imgBroadcastList = fileList
   },
       // ----------以下为导入Excel数据功能--------------
   // 文件选择回调
   onChange(file, fileList) {
    //  console.log(fileList);
     this.fileData = file; // 保存当前选择文件
     this.readExcel(); // 调用读取数据的方法
   },
   // 读取数据
   readExcel(e) {
     let that = this;
     const files = that.fileData;
    //  console.log(files);
     if (!files) {
       //如果没有文件
       return false;
     } else if (!/\.(xls|xlsx)$/.test(files.name.toLowerCase())) {
       this.$message.error("上传格式不正确，请上传xls或者xlsx格式");
       return false;
     }
     const fileReader = new FileReader();
    //  console.log(fileReader)
     fileReader.onload = ev => {
       try {
         const data = ev.target.result;
        //  console.log(ev.target)
        //  console.log(this);
         const workbook = this.XLSX.read(data, {
           type: "binary"
         });
        //  if (workbook.SheetNames.length >= 1) {
        //    this.$message({
        //      message: "导入数据表格成功",
        //      showClose: true,
        //      type: "success"
        //    });
        //  }
         const wsname = workbook.SheetNames[0]; //取第一张表
         const ws = this.XLSX.utils.sheet_to_json(workbook.Sheets[wsname]); //生成json表格内容
        //  this.$axios({
        //    url:this.$url + '/ImportWorkerApi' ,
        //    method:'post',
        //    data: ws
        //  }).then(res=>{
        //      console.log(res.data)
        //    if(res.data.IsSucess){
        //        this.$message.success('导入成功')
        //        this.getdata()
        //    }
        //  })
        //  console.log(ws)
        //  that.outputs = []; //清空接收数据
        //  for (var i = 0; i < ws.length; i++) {
        //     // console.log(ws[i]['NAME'])
        //    var sheetData = {
        //      // 键名为绑定 el 表格的关键字，值则是 ws[i][对应表头名]
        //     //  ID: ws[i]["ID"],
        //      NAME: ws[i]["NAME"],
        //      VILLAGE_NAME: ws[i]["VILLAGE_NAME"],
        //      WORKTYPE: ws[i]["WORKTYPE"],
        //      PHONE: ws[i]["PHONE"],
        //      IDCARD: ws[i]["IDCARD"],
        //      CHECKCODE: ws[i]["CHECKCODE"],
        //     //  WEIGHT_YH: ws[i]['重量'],
        //      WECHAT: ws[i]["WECHAT"],
        //      REMARK: ws[i]['REMARK'],
        //    };
        //  }
          let exceldata =  [] 
         ws.filter(item=>{
             var sheetData = {
              NAME: item["指导员姓名"],
              VILLAGE_NAME: item["负责小区"],
              WORKTYPE: item['人员类型'],
              PHONE: item['手机号'],
              IDCARD: item["身份证号码"],
              CHECKCODE: item["授权码"],
              WECHAT: item["微信号"],
              REMARK: item["备注"],
           }
             console.log(sheetData);
             exceldata.push(sheetData)
         })
         console.log(exceldata)
        this.$axios({
          url: this.$url + '/ImportWorkerApi',
          method: 'post',
          data: exceldata
        }).then(res=>{
            console.log(res)
          if(res.data.IsSucess){
            this.$message.success('导入成功')
            this.getdata()
          }
        })
         this.$refs.upload.value = "";
       } catch (e) {
         return false;
       }
     };
     // 如果为原生 input 则应是 files[0]
     fileReader.readAsBinaryString(files.raw);
   },
        async getdata(){
            var url = this.$url + '/GetCollectorListApi?CLIENT_NO=' + localStorage.getItem('clentno')
            const { data } = await this.$axios.get(url)
            this.tableData=data
        },
         async getselect(){
            const { data } = await this.$axios.get(this.$url+'/GetRegionListApi')
            this.options = data.filter(item => {
              return item
            })
        },
        async changevalue(e){
            const { data } =await this.$axios.get(this.$url+'/sreetListsApi?id='+e);
            this.optionsstreet = data.filter(item => {
                return item 
            })

        },
        async changecommunitvalue(e){
            console.log(e)
            const { data } =await this.$axios.get(this.$url+'/communityListsApi?id='+e);
            this.optionscommunit = data.filter(item => {
                // console.log(item)
                return item 
            })

        },
        async changeplot(e){
            console.log(e)
            const { data } =await this.$axios.get(this.$url+'/villageListsApi?id='+e);
            this.optionsplot = data.filter(item => {
                // console.log(item)
                return item 
            })
        },

        // 导出功能
        exportToExcel(){
            require.ensure([],()=>{
              const {export_json_to_excel} = require('../../excel/export2Excel');
              const tHeader = ['指导员姓名','负责小区', '人员类型','手机号','身份证号码','授权码','微信号','备注'];
              const filterVal = ['NAME','PARENT_ID', 'WORKTYPE','PHONE','IDCARD','CHECKCODE','WECHAT','REMARK'];
              const list = this.tableData;
              const data = this.formatJson(filterVal, list);
              console.log(data)
              export_json_to_excel(tHeader, data, "指导员信息表");
            });
        },
        formatJson(filterVal, jsonData) {
            return jsonData.map(v => filterVal.map(j => v[j]));
        },
        addlistdatadiglog(){
            this.addeditVisible = true
        },
        addsaveEdit(addform){
            console.log(this.addform);
            this.$axios({
                url:this.$url + '/AddCollectorlApi',
                // url:'http://192.168.1.113:6607/GarbagePointsTYApi/BasicData/AddCollectorlApi',
                method: 'post',
                data:{
                    Collector_NAME: this.addform.NAME,
                    PHONE: this.addform.PHONE,
                    PWD: this.addform.PWD,
                    STREET_ID: this.addform.STREET_ID,
                    COMMUNITY_ID: this.addform.COMMUNITY_ID,
                    VILLAGE_ID: this.addform.VILLAGE_ID,
                    REMARK: this.addform.REMARK
                }
            }).then((res)=>{
                console.log(res)
                if(res.data.IsSucess){
                    this.$message.success('新增成功');
                    this.getdata()
                }
            })
            this.addeditVisible =false
        },
         mohu() {
            var search = this.searchform.name;
            console.log(search)
            var newdate = [];
            if(search){
                if(search)
                 this.tableData.filter(item=>{
                     console.log(item)
                    if(item.name.indexOf(search) != -1){
                        newdate.push(item)
                    }
                })
            }else if (search == ''){
                this.getdata()
            }
            this.tableData = newdate
        },
        // 编辑操作
        handleEdit(index, row) {
            this.editform = Object.assign({},row)
            this.editVisible = true;
        },
        async handleDelete(index, row) {
            console.log(row)
            var url = this.$url + '/DeleteCollectorApi?ID=' + row.Collector_ID
            const { data } = await this.$axios.get(url)

            this.tableData.splice(index, 1);
        },
        // 保存编辑
        saveEdit() {
            var aa = {
                    Collector_ID: this.editform.Collector_ID,
                    Collector_NAME: this.editform.Collector_NAME,
                    PHONE: this.editform.PHONE,
                    PWD: this.editform.PWD,
                    STREET_ID: this.editform.STREET_ID,
                    COMMUNITY_ID: this.editform.COMMUNITY_ID,
                    VILLAGE_ID: this.editform.VILLAGE_ID,
                    REMARK: this.editform.REMARK
                }
            this.$axios({
                url: this.$url + '/UpdateCollectorApi',
                method: 'post',
                data: aa
            }).then(item=>{
                // this.$message.success('编辑成功')
                    this.getdata()
            })
            this.editVisible = false;
        },
        // 分页导航
        handlePageChange(currentPage) {
            this.currentPage = currentPage;
            console.log(this.currentPage)
            // this.$set(this.query, 'pageIndex', val);
            // this.getData();
        },
        handleSizeChange(size){
            this.pageSize = size;
            console.log(this.pageSize)
        },
        routerhandleEdit(){
            this.$router.push('/plotintegral')
        }
    }
}
</script>
<style scoped>
    .el-select{
        width: 100%;
    }
    /deep/.el-upload__input{
    display: none!important;
}
/deep/.el-upload__input{
    display: none;
}
/deep/.el-form-item__content{
    display: flex;
}
</style>